import random
import sqlite3
import time
import requests
from GetProxies import IpPool

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0",
    "Referer": "https://space.bilibili.com/1986726145",
    "Origin": "https://space.bilibili.com",
    "Host": "api.bilibili.com",
    "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
}

ipPool = IpPool()

url = "https://api.bilibili.com/x/web-interface/card"

if __name__ == "__main__":
    ipPool.crawl(1)
    # 清空表
    connection = sqlite3.connect("users.db")
    cursor = connection.cursor()
    cursor.execute(r"drop table users")
    cursor.execute("""
create table users
(
    id       integer     not null
        constraint users_pk
            primary key autoincrement,
    uid      integer     not null,
    name     varchar(20) not null,
    sex      varchar(10) not null,
    sign     varchar(50) not null,
    follower integer     not null
);""")
    connection.commit()
    cursor.close()
    # 爬取[n,m]范围内的用户信息
    n = int(input("起始UID："))
    m = int(input("终点UID："))
    for i in range(n, m + 1):
        r = requests.get(url,
                         headers=headers, params={"mid": i},
                         proxies=ipPool.ipList[random.randint(0, len(ipPool.ipList) - 1)]
                         )
        if r.json()["code"] != 0:
            continue
        data = r.json()["data"]
        card = data["card"]
        params = (card["mid"], card["name"], card["sex"], card["sign"], data["follower"])
        connection = sqlite3.connect("users.db")
        cursor = connection.cursor()
        cursor.execute(r"insert into users (uid,name,sex,sign,follower) values (?,?,?,?,?)", params)
        connection.commit()
        cursor.close()
        time.sleep(1)
    connection.close()
